package com.fyhdxxl.mz.wxapi;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.fyhdxxl.mz.R;
import com.lz.uikit.Constants;
import com.lz.uikit.GameUtils;
import com.lz.uikit.Util;
import com.tencent.mm.opensdk.modelmsg.GetMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.cocos2dx.javascript.AppActivity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class WXSDK {
    // IWXAPI 是第三方app和微信通信的openApi接口
    private static final int THUMB_SIZE = 150;
    private static IWXAPI api;
    public static Bundle bundle;
    public static AppActivity app;
    public static void Init(AppActivity activity){
        app = activity;
        api = WXAPIFactory.createWXAPI(activity, Constants.APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(Constants.APP_ID);
    }

    //授权请求
    public static void SendAuthRequest(String scope,String state){
        if(GameUtils.isWeixinAvilible(app) == false){
            app.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(app, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
                }
            });
        }else{
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = scope;
            req.state = state;
            api.sendReq(req);
        }
    }

    /**
     * 加强版分享
     */
    public static void WxShareImageEx(String info){
        if(GameUtils.isWeixinAvilible(app) == false) {
            app.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(app, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
                }
            });
        }else{
            JSONObject json = null;
            Boolean isDontFirend = true;
            String path = "";
            int width = 0,height = 0;
            int scene = SendMessageToWX.Req.WXSceneSession;
            try {
                json = new JSONObject(info);
                isDontFirend = json.getBoolean("isFirend");//类型
                path = json.getString("path");//类型
                width = json.getInt("width");//类型
                height = json.getInt("height");//类型

            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(isDontFirend == false){
                scene = SendMessageToWX.Req.WXSceneTimeline;
            }
            File file = new File(path);
            if (!file.exists()) {
                System.out.println("没找到路径"+path);
                return;
            }
            Bitmap bmp = BitmapFactory.decodeFile(path);
            Bitmap bpm = Bitmap.createScaledBitmap(bmp, 750, 1334, true);
            WXMediaMessage msg = new WXMediaMessage();
            WXImageObject imgObj = new WXImageObject(bpm);
            msg.mediaObject = imgObj;
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bpm, 150, 150, true);
            bpm.recycle();
            bmp.recycle();
            msg.thumbData = Util.bmpToByteArrayPNG(thumbBmp, true);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            req.scene = scene;
            api.sendReq(req);
        }
    }

    public static void WxShareImage(String info){

        if(GameUtils.isWeixinAvilible(app) == false){
            app.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(app, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
                }
            });
        }else{
            JSONObject json = null;
            Boolean isDontFirend = true;
            int scene = SendMessageToWX.Req.WXSceneSession;
            try {
                json = new JSONObject(info);
                isDontFirend = json.getBoolean("isFirend");//类型
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(isDontFirend == false){
                scene = SendMessageToWX.Req.WXSceneTimeline;
            }

            Bitmap bmp = BitmapFactory.decodeResource(app.getResources(), R.drawable.share);
            //初始化 WXImageObject 和 WXMediaMessage 对象
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 750, 1334, true);
            WXImageObject imgObj = new WXImageObject(thumbBmp);
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;
            //设置缩略图

            Bitmap thumbBmp2 = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
            msg.thumbData = Util.bmpToByteArrayJPG(thumbBmp2, true);
            bmp.recycle();
            //构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            req.scene = scene;
            api.sendReq(req);

        }
    }


    public  static  String getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        Uri contentUri = FileProvider.getUriForFile(context,
                "com.fyhdxxl.mz",  // 要与`AndroidManifest.xml`里配置的`authorities`一致，假设你的应用包名为com.example.app
                file);
        // 授权给微信访问路径
        context.grantUriPermission("com.tencent.mm",  // 这里填微信包名
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return contentUri.toString();   // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }

    // 判断微信版本是否为7.0.13及以上
    public static boolean checkVersionValid(Context context) {
        return api.getWXAppSupportAPI() >= 0x27000D00;
    }

    // 判断Android版本是否7.0及以上
    public static boolean checkAndroidNotBelowN() {
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N;
    }


    //压缩图片
    public  static Bitmap createBitmapThumbnail(Bitmap bitmap,boolean needRecycler) {
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int newWidth=80;
        int newHeight=80;
        float scaleWidth=((float)newWidth)/width;
        float scaleHeight=((float)newHeight)/height;
        Matrix matrix=new Matrix();
        matrix.postScale(scaleWidth,scaleHeight);
        Bitmap newBitMap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
        if(needRecycler)bitmap.recycle();
        return newBitMap;
    }

        //WxShareURL
    public static void WxShareURL(String info){
        JSONObject json = null;
        String url = "";
        String title = "";
        String  des = "";
        Boolean isFirend = false;
        int scene = SendMessageToWX.Req.WXSceneSession;
        try {
            json = new JSONObject(info);
            url = json.getString("url");//玩家uid
            title = json.getString("title");//类型
            des = json.getString("des");//类型
            isFirend = json.getBoolean("isFirend");//类型
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(isFirend == true){
            scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = des ;
        Bitmap bmp = BitmapFactory.decodeResource(app.getResources(), R.drawable.share);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        msg.thumbData = Util.bmpToByteArrayJPG(thumbBmp, true);
        bmp.recycle();
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = scene;
        api.sendReq(req);
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private static String getTransaction() {
        try {
            final GetMessageFromWX.Req req = new GetMessageFromWX.Req(bundle);
            return req.transaction;
        } catch (Exception e) {
            return "";
        }
    }


}
